using Microsoft.AspNetCore.Mvc;
using TerritoryGame.Application.Interfaces;
using TerritoryGame.Domain.Entities.App;
using TerritoryGame.Application.Commands;

namespace TerritoryGame.Api.Controllers
{
    [ApiController]
    [Route("api/game-history")]
    public class GameHistoryController : ControllerBase
    {
        private readonly IAppGameHistoryService _gameHistoryService;

        public GameHistoryController(IAppGameHistoryService gameHistoryService)
        {
            _gameHistoryService = gameHistoryService;
        }

        /// <summary>
        /// 获取全局游戏历史（根路由）
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<ApiResult<List<GameRecord>>>> GetGlobalHistory(
            [FromQuery] int page = 1, 
            [FromQuery] int pageSize = 20)
        {
            try
            {
                if (page < 1 || pageSize < 1 || pageSize > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "页码必须大于0，页面大小必须在1-100之间"));
                }

                var history = await _gameHistoryService.GetGlobalHistoryAsync(page, pageSize);
                return Ok(ApiResult.Success("获取全局游戏历史成功", history));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取全局游戏历史失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取特定游戏记录
        /// </summary>
        [HttpGet("{gameId}")]
        public async Task<ActionResult<ApiResult<GameRecord>>> GetGameRecord(string gameId)
        {
            try
            {
                var record = await _gameHistoryService.GetGameRecordAsync(gameId);
                if (record == null)
                {
                    return NotFound(ApiResult.Failed(404, "游戏记录不存在"));
                }

                return Ok(ApiResult.Success("获取游戏记录成功", record));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取游戏记录失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取玩家游戏历史
        /// </summary>
        [HttpGet("player/{playerId}")]
        public async Task<ActionResult<ApiResult<List<GameRecord>>>> GetPlayerHistory(
            string playerId, 
            [FromQuery] int page = 1, 
            [FromQuery] int pageSize = 20)
        {
            try
            {
                if (page < 1 || pageSize < 1 || pageSize > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "页码必须大于0，页面大小必须在1-100之间"));
                }

                var history = await _gameHistoryService.GetPlayerHistoryAsync(playerId, page, pageSize);
                return Ok(ApiResult.Success("获取玩家游戏历史成功", history));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取玩家游戏历史失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取房间游戏历史
        /// </summary>
        [HttpGet("room/{roomId}")]
        public async Task<ActionResult<ApiResult<List<GameRecord>>>> GetRoomHistory(
            string roomId, 
            [FromQuery] int page = 1, 
            [FromQuery] int pageSize = 20)
        {
            try
            {
                if (page < 1 || pageSize < 1 || pageSize > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "页码必须大于0，页面大小必须在1-100之间"));
                }

                var history = await _gameHistoryService.GetRoomHistoryAsync(roomId, page, pageSize);
                return Ok(ApiResult.Success("获取房间游戏历史成功", history));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取房间游戏历史失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 保存游戏记录
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<ApiResult<bool>>> SaveGameRecord([FromBody] GameRecord record)
        {
            try
            {
                if (record == null)
                {
                    return BadRequest(ApiResult.Failed(400, "游戏记录不能为空"));
                }

                var result = await _gameHistoryService.SaveGameRecordAsync(record);
                if (result)
                {
                    return Ok(ApiResult.Success("游戏记录保存成功", result));
                }
                else
                {
                    return StatusCode(500, ApiResult.Failed(500, "游戏记录保存失败"));
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"保存游戏记录失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除游戏记录
        /// </summary>
        [HttpDelete("{gameId}")]
        public async Task<ActionResult<ApiResult<bool>>> DeleteGameRecord(string gameId)
        {
            try
            {
                var result = await _gameHistoryService.DeleteGameRecordAsync(gameId);
                if (result)
                {
                    return Ok(ApiResult.Success("游戏记录删除成功", result));
                }
                else
                {
                    return NotFound(ApiResult.Failed(404, "游戏记录不存在或删除失败"));
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"删除游戏记录失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 按日期范围获取游戏历史
        /// </summary>
        [HttpGet("date-range")]
        public async Task<ActionResult<ApiResult<List<GameRecord>>>> GetHistoryByDateRange(
            [FromQuery] DateTime startDate,
            [FromQuery] DateTime endDate,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                if (startDate >= endDate)
                {
                    return BadRequest(ApiResult.Failed(400, "开始日期必须早于结束日期"));
                }

                if (page < 1 || pageSize < 1 || pageSize > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "页码必须大于0，页面大小必须在1-100之间"));
                }

                var history = await _gameHistoryService.GetHistoryByDateRangeAsync(startDate, endDate, page, pageSize);
                return Ok(ApiResult.Success("按日期范围获取游戏历史成功", history));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"按日期范围获取游戏历史失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取游戏总数
        /// </summary>
        [HttpGet("count/total")]
        public async Task<ActionResult<ApiResult<int>>> GetTotalGameCount()
        {
            try
            {
                var count = await _gameHistoryService.GetTotalGameCountAsync();
                return Ok(ApiResult.Success("获取游戏总数成功", count));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取游戏总数失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取玩家游戏数量
        /// </summary>
        [HttpGet("count/player/{playerId}")]
        public async Task<ActionResult<ApiResult<int>>> GetPlayerGameCount(string playerId)
        {
            try
            {
                var count = await _gameHistoryService.GetPlayerGameCountAsync(playerId);
                return Ok(ApiResult.Success("获取玩家游戏数量成功", count));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取玩家游戏数量失败: {ex.Message}"));
            }
        }
    }
}
